<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>客服聊天框</title>
    <link rel="stylesheet" href="../customer_service/chatting.css" />
</head>

<body>
    <div id="app">
        <div class="chatting">
            <!-- 左侧列表 -->
            <!-- <div class="list" v-if="userInfo.identity != 2">
                <el-transfer v-model="value" :data="userList"></el-transfer>
            </div> -->
            <!-- 右侧聊天框 -->
            <div class="chatWindow">
                <div class="word">聊天窗口</div>
                <el-row :gutter="20">
                    <el-col :span="12" :offset="6">
                        <div class="main">
                            <el-row>
                                <el-input placeholder="请输入自己的昵称" prefix-icon="el-icon-user-solid" v-model="name"
                                    style="width:50%" class="text"></el-input>
                                <el-button type="primary" @click="conectWebSocket()">建立连接</el-button>
                                <el-button type="danger" @click="onClose()">断开连接</el-button>
                                <el-button type="danger" @click="quitToIndex()">返回</el-button>

                            </el-row>
                            <el-row>
                                <el-input placeholder="请输入对方频道号" prefix-icon="el-icon-phone" v-model="aisle"
                                    style="width:40%" class="text"></el-input>
                            </el-row>
                            <el-row>
                                <el-input placeholder="请输入要发送的消息" prefix-icon="el-icon-s-promotion"
                                    v-model="messageValue" style="width:50%" class="text"></el-input>
                                <el-button type="primary" @click="sendMessage()">发送</el-button>
                            </el-row>
                            <div class="message">
                                <!-- 对发送来的消息对象进行判断，如果是本人  就向右浮动  如果是其他人就向左浮动 -->
                                <div v-for="(value,key,index) in messageList" :key="index">
                                    <div class="my">
                                        <el-avatar v-if="value.nickname==name" style="float:right"
                                            src="https://img1.baidu.com/it/u=3438742520,3870787236&fm=253&fmt=auto&app=138&f=PNG?w=500&h=500">
                                        </el-avatar>
                                        <el-tag class="txt" v-if="value.nickname==name" type="success"
                                            style="float:right"> 我：{{value.msg}}</el-tag>
                                        <br />
                                    </div>

                                    <!-- {{value.nickname}} -->
                                    <div class="test">
                                        <el-avatar class="img" v-if="value.nickname!=name"
                                            src="https://img2.baidu.com/it/u=333016990,977824001&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500">
                                        </el-avatar>
                                        <el-tag class="imagename test_txt" v-if="value.nickname!=name">
                                            {{value.nickname}} ： {{value.msg}}</el-tag>
                                        <br />
                                    </div>

                                </div>
                            </div>
                        </div>
                    </el-col>
                </el-row>
            </div>
        </div>

    </div>
    <!--引用vue.js文件-->
    <script src="/js/untils/axios-0.18.0.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!--引用axius异步请求封装-->
    <script src="/js/untils/vue.js"></script>
    <!--引用element-ui-->
    <script src="/js/untils/index.js"></script>
    <script>
        new Vue({
            el: '#app',
            data() {
                const generateData = _ => {
                    const data = [];
                    // for (let i = 1; i <= data.length; i++) {
                    for (let i = 1; i <= 25; i++) {
                        data.push({
                            key: i,
                            label: `用户 ${ i }`,
                            // disabled: i % 4 === 0
                        });
                    }
                    return data;
                };

                return {
                    name: '', //昵称
                    websocket: '', //websocket对象
                    aisle: '', //对方频道号
                    messageValue: '', //消息内容
                    messageList: [], //消息列表
                    //左侧消息列表
                    userList: generateData(),
                    value: [1, 4],

                    // 用户信息
                    userInfo: {
                        identity: 0, // 身份
                        nickName: "", // 昵称
                        spare01: '',
                        spare02: '',
                        userAdmin: '', // 账号
                        userId: 0,
                    },

                }
            },
            methods: {
                //建立连接
                conectWebSocket() {
                    // console.log("连接已建立！")
                    // 如果  当前的用户  不存在  出现提示  存在
                    if (this.name === "") {
                        this.$alert("请输入自己的昵称", "提示", {
                            confirm: '确定',
                            cancelIdleCallback: active => {}
                        });
                    } else {
                        // 判断当前浏览器是否支持webSocket
                        if ("WebSocket" in window) {
                            this.websocket = new WebSocket(
                                "ws://localhost:8080/websocket/" + this.name + "&" + this.userInfo.userAdmin
                            )
                        } else {
                            alert("不支持webSocket连接！")
                        }
                        // 连接发生错误的回调方法
                        this.websocket.onerror = function () {

                        };
                        // 连接成功的回调方法
                        this.websocket.onopen = function (event) {

                        };
                        // 接收到消息的回调方法
                        var that = this //异步请求
                        this.websocket.onmessage = function (event) {
                            var object = eval("(" + event.data + ")");
                            console.log(object);
                            // 判断消息类型  如果是 0  群聊
                            //                     1  单聊
                            // debugger

                            if (object.type == 0) { // 群聊
                                // 提示连接成功
                                console.log("连接成功！");
                                that.showInfo(object.people, object.aisle)
                            }

                            if (object.type == 1) { // 单聊
                                //显示消息
                                console.log("接受消息");
                                that.messageList.push(object);
                                // debugger
                                console.log(that.messageList)
                                // that.showInfo(object.people, object.aisle)
                            }

                            // debugger
                            // //显示消息
                            // console.log("接受消息");
                            // console.log(that.messageList)
                            // that.messageList.push(object);
                            // // debugger
                            // console.log(that.messageList)
                            // that.showInfo(object.people, object.aisle)

                        };
                        // 连接关闭的回调方法
                        this.websocket.onclose = onClose();
                        // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket
                        window.onbeforeunload = function () {
                            this.websocket.close();
                        };
                    }
                },
                //发送消息
                sendMessage: function () {
                    // debugger
                    var socketMsg = {
                        msg: this.messageValue,
                        toUser: this.aisle,
                        fromUser: this.userInfo.nickName
                    }; //?
                    if (this.aisle == "") { //对方频道号 是空  
                        // 群聊
                        socketMsg.type = 0;

                    } else {
                        // 单聊
                        socketMsg.type = 1;
                    }
                    this.websocket.send(JSON.stringify(socketMsg));
                },

                // 展示聊天室信息
                showInfo: function (people, aisle) {
                    this.$notify({
                        title: '当前的在线人数 ：' + people,
                        message: '你的频道号 ：' + aisle,
                        duration: 0
                    });
                },

                // 根据用户账号查询用户信息
                getUserInfoByUserAdmin(userAdmin) {
                    var that = this
                    axios({
                        method: "get",
                        url: "http://localhost:8080/customerServiceUser/getUserInfoByUserAdmin" +
                            "?userAdmin=" + userAdmin
                    }).then(function (resp) {
                        // console.log(resp)
                        that.userInfo = resp.data.data
                        that.name = that.userInfo.nickName
                        console.log(that.userInfo)
                    })
                },

                onClose() {
                    //
                    this.websocket.close()
                    alert("关闭连接!")
                },

                // 退出到首页
                quitToIndex() {
                    window.localStorage.setItem(this.userInfo.userAdmin,JSON.stringify(this.userInfo))
                    window.localStorage.setItem(this.userInfo.userAdmin,JSON.stringify(this.userInfo))
                    // 跳转到主页
                    if (this.userInfo.identity == 2) window.location.href = "../../index/index.html?phone=" +
                        this.userInfo.spare01
                    else window.location.href = "../coupon.html?userAdmin" + this.userInfo.nickName
                }

            },

            // 进入页面就执行
            created() {

            },

            // 页面加载完再执行
            mounted() {
                // 取出缓存中的用户数据
                var url = decodeURI(window.location.href);
                var userAdmin = url.split("?userAdmin=")[1];
                console.log(userAdmin);
                if (userAdmin != null) this.getUserInfoByUserAdmin(userAdmin)
            },
        })
    </script>
</body>

</html>